package com.lagou.springboot.work.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.LocaleResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

//@Configuration
public class LanguageLocaleResolver implements LocaleResolver {
    @Override
    public Locale resolveLocale(HttpServletRequest httpServletRequest) {
        String language = httpServletRequest.getParameter("language");
        Locale locale = null;
        if (!StringUtils.isEmpty(language)) {
            String[] split = language.split("-");
            locale = new Locale(split[0], split[1]);
        } else {
            // Accept-Language: zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7
            String acceptLanguage = httpServletRequest.getHeader("Accept-Language");

            String[] split = acceptLanguage.split(",")[0].split("-");
            locale = new Locale(split[0], split[1]);
        }
        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {

    }

    @Bean
    public LocaleResolver localeResolver() {
        return new LanguageLocaleResolver();
    }

}
